package mx.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import mx.entity.PageBean;
import mx.entity.Product;
import mx.service.ProductService;
import mx.utils.DateJsonValueProcessor;
import mx.utils.ResponseUtil;
import mx.utils.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 产品
 * 
 * @author Gray-bird
 * 
 */
@Controller
@RequestMapping("/product")
public class ProductController {

	@Resource
	private ProductService productService;

	@RequestMapping("/list")
	public String list(
			@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows,
			Product product, HttpServletResponse response) throws Exception {
		PageBean pageBean = new PageBean(Integer.parseInt(page),
				Integer.parseInt(rows));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", StringUtil.formatLike(product.getName()));
		map.put("type", StringUtil.formatLike(product.getType()));
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());
		List<Product> employeeList = productService.list(map);
		long totatl = productService.getTotal(map);
		JSONObject result = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(employeeList, jsonConfig);
		result.put("rows", jsonArray);
		result.put("total", totatl);
		ResponseUtil.write(response, result);
		return null;
	}

	@RequestMapping(value = "/delete")
	public String deleteEmpById(
			@RequestParam(value = "ids", required = false) String ids,
			HttpServletResponse response) throws Exception {
		String[] id = ids.split(",");
		JSONObject result = new JSONObject();
		for (String ProductId : id) {
			productService.delete(Integer.parseInt(ProductId));
		}
		result.put("success", true);
		ResponseUtil.write(response, result);
		return null;
	}

	/**
	 * 添加或者修改员工
	 * 
	 * @return
	 */
	@RequestMapping("/save")
	public String save(Product product, HttpServletResponse response)
			throws Exception {
		int resultTotal = 0;
		JSONObject result = new JSONObject();
		if (product.getId() == null) {
			resultTotal = productService.add(product);
		} else {
			resultTotal = productService.update(product);
		}
		if (resultTotal > 0) {
			result.put("success", true);
		} else {
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
		return null;
	}

}
